package cn.com.connected.service.impl;

import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.common.utils.HttpUtil;
import cn.com.connected.service.WeChatCommonService;
import cn.com.connected.service.WeChatMessageService;
import cn.com.connected.vo.wechat.WeChatMessageValid;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatMessageServiceImpl implements WeChatMessageService {

    public static WeChatMessageService weChatMessageService;

    @Resource
    private WeChatCommonService weChatCommonService;

    @Resource
    private HttpUtil httpUtil;

    @Value("${wechat.url.messagepush}")
    private String messagePushUrl;

    private static String  token = "message2022push";

    @PostConstruct
    void init(){
        WeChatMessageServiceImpl.weChatMessageService = this;
    }

    @Override
    public boolean checkSignature(WeChatMessageValid message) {
        try{
            String signature = message.getSignature();
            String timestamp = message.getTimestamp();
            String nonce = message.getNonce();


            //将token、timestamp、nonce三个参数进行字典排序
            String[] arr = new String[] {token, timestamp, nonce};
            Arrays.sort(arr);

            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.length; i++) {
                content.append(arr[i]);
            }

            MessageDigest md = null;
            String tmpStr = null;

            try {
                md = MessageDigest.getInstance("SHA-1");
                // 将三个参数字符串拼接成一个字符串进行sha1加密
                byte[] digest = md.digest(content.toString().getBytes());
                tmpStr = byteToStr(digest);
            } catch (NoSuchAlgorithmException e) {
                log.error(e.getMessage());
                throw new BusinessException(ErrorCode.SYSTEM_FAIL);
            }
            log.info("tmpStr:{} signature:{}" ,tmpStr,signature);
//            return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) ? message.getEchostr() : "" : "";
            return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;

        }catch (Exception e){
            log.error(e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_FAIL);
        }
    }


    @Override
    public void pushMessage(String openId, String tempId, Map message) {
        log.info("start send message : {} {} {}",openId,tempId,JSONObject.toJSON(message));
        Map body=new HashMap();
        body.put("touser",openId);
        body.put("template_id",tempId);

        body.put("data",message);
        //发送
        String accessToken= weChatCommonService.getAccessToken();
        JSONObject o = httpUtil.post(String.format(messagePushUrl,accessToken),body,null);
        log.info(o.toJSONString());

    }

    /**
     * 将字节数组转换为十六进制字符串
     * @param byteArray
     * @return
     */
    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     * @param mByte
     * @return
     */
    private String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }
}
